package com.zb.api.business.service.impl;


import com.zb.api.business.dto.TestDto;
import com.zb.api.business.mapper.TestMapper;
import com.zb.api.business.service.TestService;
import com.zb.api.utils.BatchInsertUtil;
import com.zb.api.utils.MybatisBatchExecutor;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;



@Service
public class TestServiceImpl implements TestService {


    @Autowired
    private TestMapper testMapper;

    @Autowired
    SqlSessionFactory sqlSessionFactory;


    private Logger logger = LoggerFactory.getLogger(TestServiceImpl.class);

    @Override
    public int insert(List<TestDto> testDtos){
        long startTime = System.currentTimeMillis();
        for (TestDto testDto : testDtos) {
            testMapper.insert(testDto);
        }
        long endTime = System.currentTimeMillis();
        logger.info(testDtos.size()+"条数据, 一条条插入 SQL 耗费时间 {}", (endTime - startTime));
        return 1;
    }

    @Override
    public void insertBatch(List<TestDto> testDtos) {
        long startTime = System.currentTimeMillis();
        testMapper.insertBatch(testDtos);
        long endTime = System.currentTimeMillis();
        logger.info(testDtos.size()+"条数据, 合并成一条 SQL 插入耗费时间 {}", (endTime - startTime));
    }


    @Override
    public void insertByOneAndOne(List<TestDto> testDtos){
        long startTime = System.currentTimeMillis();
        /*SqlSession session = sqlSessionFactory.openSession(ExecutorType.BATCH);
        TestMapper  mapper = session.getMapper(TestMapper.class);
        for (int i = 0 ; i < testDtos.size() ; i++){
            mapper.insert(testDtos.get(i));
            if(i%5000==4999){//每5000条提交一次防止内存溢出   提交后无法回滚
                session.commit();
                session.clearCache();
            }
        }
        session.commit();
        session.clearCache();*/
        BatchInsertUtil.batchInsert(testDtos, TestMapper.class, TestMapper::insert);
        long endTime = System.currentTimeMillis();
        logger.info(testDtos.size()+"条数据, 批量一条条插入 SQL 耗费时间 {}", (endTime - startTime));
    }


}
